package face.pay.security.service.impl;

import face.pay.dao.OemInfoDao;
import face.pay.dao.RoleInfoDao;
import face.pay.dao.UserInfoDao;
import face.pay.entity.OemInfo;
import face.pay.entity.RoleInfo;
import face.pay.entity.UserInfo;
import face.pay.security.entity.SecurityUser;
import face.pay.security.service.ISecurityUserService;
import face.pay.vo.OemUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class ISecurityUserServiceImpl implements ISecurityUserService {

    @Autowired
    private OemInfoDao oemInfoDao;

    @Autowired
    private UserInfoDao userDao;

    @Autowired
    private RoleInfoDao roleDao;


    @Autowired
    private SessionRegistry sessionRegistry;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //第一步：通过用户名，去数据库查询用户信息
        //第二步：根据用户信息，实例化，处理自己的用户对象封装成UserDetails
        //如果是使用未加密的帐号和密码校验，请在用户名和密码前面，添加一个标识{noop}
        //  User user=new User(userInfo.getUsername(),"{noop}"+userInfo.getPassword(),getAuthority(userInfo.getRoles()));
        UserInfo userInfo = this.userDao.getByUserName(username);

        List<Object> o = sessionRegistry.getAllPrincipals();
        for ( Object principal : o) {
            /*if (principal instanceof SysUser && (user.getUsername().equals(((SysUser) principal).getUsername()))) {
                throw new SessionAuthenticationException("当前用户已经在线，登录失败！！！");
            }*/
        }

        if(userInfo!=null){
            if (userInfo.getDeleted() == 1) {
                throw new UsernameNotFoundException("此帐号已被注销");
            }
            if (userInfo.getState() != 1) {
                throw new UsernameNotFoundException("帐号异常，请与服务商联系");
            }
            List<RoleInfo> roles  = this.roleDao.getUserRoleByUserId(userInfo.getId());
            SecurityUser user=new SecurityUser(userInfo.getUserName(),userInfo.getPassWord(),getAuthority(roles));
            user.setCurrentUser(userInfo);
            user.setUserId(userInfo.getId());
            return  user;

        }else{
            throw  new UsernameNotFoundException("用户名或密码错误");
        }

    }

    @Override
    public UserDetails loadUser(String username, String domain) throws UsernameNotFoundException {
        //第二步：根据用户信息，实例化，处理自己的用户对象封装成UserDetails
        //如果是使用未加密的帐号和密码校验，请在用户名和密码前面，添加一个标识{noop}
        OemInfo info =  new OemInfo();

        info.setAdminDomain(domain);

        log.info("domain:"+domain);
        log.info("username:"+username);

        if(StringUtils.isBlank(domain)){
            throw  new UsernameNotFoundException("非法操作 立即停止");
        }
        OemInfo oemInfo =  this.oemInfoDao.getOemInfo(info);
        if(oemInfo==null){
            throw  new UsernameNotFoundException("登录失败,联系管理员");
        }

        UserInfo userInfo = this.userDao.getByUserNameAndOemId(username,oemInfo.getId());


        if(userInfo!=null){
            if (userInfo.getDeleted() == 1) {
                throw new UsernameNotFoundException("此帐号已被注销");
            }
            if (userInfo.getState() != 1) {
                throw new UsernameNotFoundException("帐号异常，请与服务商联系");
            }
            List<RoleInfo> roles  = this.roleDao.getUserRoleByUserId(userInfo.getId());
            SecurityUser user=new SecurityUser(userInfo.getUserName(),userInfo.getPassWord(),getAuthority(roles));
            user.setCurrentUser(userInfo);
            user.setUserId(userInfo.getId());
            return  user;

        }else{
            throw  new UsernameNotFoundException("用户名或密码错误");
        }

    }

    //作用就是返回一个List集合，集合中装入的是角色描述
    public List<SimpleGrantedAuthority> getAuthority(List<RoleInfo> roles) {

        List<SimpleGrantedAuthority> list = new ArrayList<>();
        for (RoleInfo role : roles) {
            list.add(new SimpleGrantedAuthority(role.getCode()));
        }
        return list;
    }
}
